<template>
  <div class="container" style="padding: 10px">
    <el-card>
      <el-form class="demo-form-inline">
        <el-form-item label="学科名称">
          <el-row type="flex" justify="space-between" align="middle">
              <el-input
                v-model="input"
                placeholder="请输入内容"
                type="text"
                style="width: 400px; margin-right: 10px"
              ></el-input>
              <el-button @click="DeleteInput">清除</el-button>
              <el-button style="margin-right: 10px" type="primary" @click="excessive">搜索</el-button>
            <el-col>
              <el-row type="flex" justify="end">
                <el-button
                  icon="el-icon-edit"
                  type="success"
                  @click="addsubjects"
                  >新增学科</el-button
                >
              </el-row>
            </el-col>
          </el-row>
        </el-form-item>
        <el-alert
        :closable="false"
        :title="`数据一共 ${counts} 条`"
        type="info"
        show-icon
      >
      </el-alert>
      </el-form>
      <br>
      <el-table :data="data" :header-cell-style="{
        background: '#FAFAFA',
        color: '#909399',
        borderBottom: '2px solid #e8e8e8',
      }">
        <el-table-column type="index" label="序号" >
        </el-table-column>
        <el-table-column prop="subjectName" label="学科名称">
        </el-table-column>
        <el-table-column prop="username" label="创建者">
        </el-table-column>
        <el-table-column prop="addDate" label="创建日期" width="150">
          <template v-slot="{ row }">
            {{
              new Date(+new Date(row.addDate) + 8 * 3600 * 1000)
                .toISOString()
                .replace(/T/g, " ")
                .replace(/\.[\d]{3}Z/, "")
            }}
          </template>
        </el-table-column>
        <el-table-column prop="isFrontDisplay" label="前台是否显示" width="120">
          <template v-slot="{ row }">
            {{ +row.isFrontDisplay ? "是" : "否" }}
          </template>
        </el-table-column>
        <el-table-column prop="twoLevelDirectory" label="二级目录" >
        </el-table-column>
        <el-table-column prop="tags" label="标签" >
        </el-table-column>
        <el-table-column prop="totals" label="题目数量" >
        </el-table-column>
        <el-table-column label="操作" prop="id" width="250">
          <template v-slot="{ row }">
            <el-button
              type="text"
              :disabled="false"
              @click="
                $router.replace(
                  `/subjects/directorys?id=${row.id}&name=${row.subjectName}`
                )
              "
              >学科分类</el-button
            >
            <el-button
              type="text"
              :disabled="false"
              @click="
                $router.replace(
                  `/subjects/tags?id=${row.id}&name=${row.subjectName}`
                )
              "
              >学科标签</el-button
            >
            <el-button type="text" :disabled="false" @click="update(row)"
              >修改</el-button
            >
            <el-button
              type="text"
              :disabled="!!row.totals"
              @click="remove({ id: row.id })"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <el-row type="flex" justify="end">
        <el-pagination
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="1"
          :page-sizes="[1, 5, 10, 20]"
          :page-size.sync="list.pagesize"
          layout=" prev, pager, next,sizes, jumper"
          :total="counts"
        >
        </el-pagination>
      </el-row>
    </el-card>
    <el-dialog
      :title="title"
      :visible.sync="dialogVisible"
      width="400px"
      @close="handleClose"
    >
      <span>
        <el-form
          :model="ruleInfo"
          :rules="rules"
          ref="ruleForm"
          label-position="right"
        >
          <el-form-item label-width="80px"  label="学科名称" prop="val">
            <el-input
              v-model.trim="ruleInfo.val"
              placeholder="请输入内容"
              type="text"
             style="width: 80%"
            ></el-input>
          </el-form-item>
          <el-form-item label-width="80px" label="是否显示">
            <el-switch
              v-model="ruleInfo.showif"
              active-color="#13ce66"
              inactive-color="#ff4949"
            >
            </el-switch>
          </el-form-item>
        </el-form>
      </span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" @click="bthOk">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { list, add, update, remove, simple } from '@/api/hmmm/subjects.js'
export default {
  data () {
    const subjectsRules = async (rule, value, callback) => {
      const { data } = await simple()
      console.log(data)
      let isRepeat
      data.forEach(item => {
        if (item.label === value) {
          isRepeat = true
        }
      })
      isRepeat ? callback(new Error('已有该学科')) : callback()
    }
    return {
      bugExcessive: '',
      title: '新增学科',
      ruleInfo: {
        showif: true,
        val: '',
        id: ''
      },
      dialogVisible: false,
      input: '',
      data: [],
      counts: null,
      list: {
        pagesize: 10,
        page: 1,
        subjectName: ''
      },
      rules: {
        val: [{ required: true, message: '请输入学科名称', trigger: 'change' },
          { min: 1, max: 10, message: '要求1-10个字符', trigger: 'blur' },
          {
            trigger: 'blur',
            validator: subjectsRules
          }]
      }
    }
  },
  created () {
    this.list1()
  },
  methods: {
    excessive () {
      this.bugExcessive = this.input
      this.subjectsSearch()
      this.list.page = 1
      // this.bugExcessive = ''
    },
    async remove (data) {
      this.$confirm('此操作将永久删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        await remove(data)
        this.list1()
        this.$message({
          message: '删除成功',
          type: 'success'
        })
      }).then(() => {
        if (this.data.length === 1) {
          console.log(666)
          this.list.page = this.list.page - 1
          if (!this.list.page) {
            this.list.page = 1
          }
          this.list1()
        } else {
          console.log(this.data[0])
        }
      }).catch((error) => {
        if (error === 'cancel') {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        } else {
          console.log(error)
        }
      })
    },
    addsubjects () {
      this.title = '新增学科'
      this.dialogVisible = true
    },
    update (row) {
      this.title = '修改学科'
      this.dialogVisible = true
      this.ruleInfo.showif = !!row.isFrontDisplay
      this.ruleInfo.val = row.subjectName
      this.ruleInfo.id = row.id
    },
    async bthOk () {
      if (this.title === '修改学科') {
        this.$refs.ruleForm.validate(async (valid) => {
          if (valid) {
            try {
              const data = {
                subjectName: this.ruleInfo.val,
                id: this.ruleInfo.id,
                isFrontDisplay: this.ruleInfo.showif
              }
              console.log(data)
              await update(data)
              this.list1()
              this.handleClose()
              this.$message({
                message: '修改成功',
                type: 'success'
              })
            } catch (error) {
              console.log(error)
            }
          } else {
            console.log('999')
            return false
          }
        })
      } else {
        this.$refs.ruleForm.validate(async (valid) => {
          if (valid) {
            try {
              const data = {
                subjectName: this.ruleInfo.val,
                isFrontDisplay: this.ruleInfo.showif ? 1 : 0
              }
              await add(data)
              this.list1()
              this.handleClose()
              this.$message({
                message: '新增成功',
                type: 'success'
              })
            } catch (error) {
              console.log(error)
            }
          } else {
            console.log('999')
            return false
          }
        })
      }
    },
    handleClose () {
      this.ruleInfo = {
        showif: true,
        val: ''
      }
      this.$refs.ruleForm.resetFields()
      this.dialogVisible = false
    },
    DeleteInput () {
      this.input = ''
      // 点击清除切跳转所有数据
      // this.bugExcessive = ''
      // this.subjectsSearch()
    },
    subjectsSearch () {
      this.list.subjectName = this.bugExcessive
      this.list1()
    },
    handleSizeChange (val) {
      this.list.pagesize = val
      this.list1()
    },
    handleCurrentChange (val) {
      this.list.page = val
      this.list1()
    },
    async list1 () {
      const { data } = await list(this.list)
      this.data = data.items
      this.counts = data.counts
      this.list.pagesize = +data.pagesize
      // console.log(data)
      // console.log(this.data)
    }
  }
}
</script>

<style scoped lang="less">
.demo-form-inline{
width: 100%;
Min-width:300px;
}
</style>
